package com.trip.file.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.trip.common.vo.Result;
import com.trip.file.service.MinIOService;
import com.trip.file.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import static com.trip.common.vo.DataDictionary.FAIL;

@Service
public class MinIOServiceImpl implements MinIOService {
    @Value("${minio.bucketName}")
    private String bucket;
    @Autowired
    private MinioUtil minioUtil;
    private String[] imageTypes = {"jpg","png","gif"};
    private long maxSize = 1024 * 1024 ;
    @Override
    public Result uploadImage(MultipartFile image) {
        String originalFilename = image.getOriginalFilename();
        String fileType = StrUtil.subAfter(originalFilename, ".", true);
        boolean flag = true;
        for(String imageType : imageTypes){
            if(imageType.equals(fileType)) {
                flag = false;
                break;
            }
        }
        if(flag) return Result.error(FAIL,"类型不符合");
        if(image.getSize() > maxSize) return Result.error(FAIL,"文件过大");
        String newFileName = minioUtil.createNewFileName(originalFilename);
        try{
            minioUtil.uploadFile(bucket,newFileName,image);
        }catch (Exception e){
            minioUtil.delete(newFileName,bucket);
            return Result.error(FAIL,e.getMessage());
        }
        String url = minioUtil.getUrl(newFileName, bucket);
        return Result.ok(url,"上传成功");
    }

}
